package com.sline.day02._02_transaction;

import com.sline.util.JdbcUtil;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class transactionTest {
    public static void main(String[] args) {
        transfer();
    }

    public static void transfer() {

        Connection connection = JdbcUtil.getConnection();

        try {
            // 关闭链接自动提交
            connection.setAutoCommit(false);

            String sql = "select * from t_bankAccount where name = ? and balance > ?;";

            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "张无忌");
            preparedStatement.setBigDecimal(2, new BigDecimal(1000));

            ResultSet rs = preparedStatement.executeQuery();
            if (!rs.next()) {
                throw new RuntimeException("账户余额不足！");
            }

            sql = "update t_bankAccount set balance = balance - ? where name = ?;";

            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setBigDecimal(1, new BigDecimal(1000));
            preparedStatement.setString(2, "张无忌");
            preparedStatement.executeUpdate();

            int a = 1 / 0;

            sql = "update t_bankAccount set balance = balance + ? where name = ?;";

            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setBigDecimal(1, new BigDecimal(1000));
            preparedStatement.setString(2, "赵敏");
            preparedStatement.executeUpdate();

            connection.commit();

            JdbcUtil.close(connection, preparedStatement, rs);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                System.out.println("事务终端，提交回滚");
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }

    }
}
